package com.atguigu.gmall.product.controller;


import com.atguigu.gmall.common.result.Result;
import jodd.io.FileNameUtil;
import org.apache.commons.io.FilenameUtils;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/admin/product")
public class FileController {

    @Value("${imgUrl}")
    private String imgUrl;

    //上传图片
    @PostMapping("/fileUpload")
    public Result fileUpload(MultipartFile file) throws Exception{

        System.out.println(file.getOriginalFilename());
        System.out.println(file.getSize());
        String path = ClassUtils.getDefaultClassLoader().
                getResource("fast_client.conf").getPath();
        //底层 IO 磁盘  绝对路径
        ClientGlobal.init(path);
        //读取resource/fast_client.conf
        //连接的上跟踪器
        TrackerClient trackerClient = new TrackerClient();

        //连接
        TrackerServer trackerServer = trackerClient.getConnection();
        //扩展
        StorageServer storageServer = null;
        //连接Storage
        StorageClient1 storageClient1 = new StorageClient1(trackerServer,storageServer);

        //扩展名
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        //上传文件
        String fileId = storageClient1.upload_file1(
                file.getBytes() ,
                ext, null);
        //System.out.println("http://192.168.200.128:8080/" + fileId);
        return Result.ok(imgUrl + fileId);
    }
}
